<?php

namespace App\Models;

use App\Handlers\KeysHandler;
use Dcat\Admin\Traits\HasDateTimeFormatter;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Cache;

class GoodsLogistic extends Model
{
    use HasFactory;
    use SoftDeletes;
    use HasDateTimeFormatter;



    protected $fillable = [
        'good_order_id',
        'message',
        'time',
        'messagesystem',
        'shipping_address_id'
    ];


    /**
     * @return BelongsTo
     */
    public function goodOrder(): BelongsTo
    {
        return $this->belongsTo(GoodsOrder::class, 'good_order_id', 'id');
    }

    /**
     * 获取订单物流信息， 缓存5分钟
     * @param $good_order_id
     * @param int $type
     * @return mixed
     */
    public static function getListByGoodId($good_order_id)
    {
        return Cache::remember(sprintf(KeysHandler::GOODS_TYPE_LOGISTICS, $good_order_id), 300, function () use ($good_order_id) {
            return self::query()->where('good_order_id', $good_order_id)->get();
        });
    }


    /**
     * 商品订单选择
     * @return array
     */
    public static function getGoodOptions(): array
    {
        $goodOrders = GoodsOrder::with('orderDetail')->where('order_status', GoodsOrder::ORDER_NOT_RECEIVED)->get(['id', 'order_sn']);
        $data = [];
        foreach ($goodOrders as $goodOrder) {
            $data[$goodOrder->id] = "{$goodOrder->orderDetail->name}--[ {$goodOrder->order_sn} ]";
        }

        return $data;
    }

}
